package com.lh.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lh.entity.Article;
import com.lh.entity.PageBean;
import com.lh.entity.Result;
import com.lh.mapper.ArticleMapper;
import com.lh.service.ArticleService;
import com.lh.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImp  implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Result addArticle(Article article) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);
      int i=  articleMapper.addArticle(article);
      if (i>0){
          return Result.success("文章新增成功");
      }else{
          return Result.error("文章新增失败");
      }

    }

    @Override
    public PageBean articleList(Integer pageNum, Integer pageSize, Integer categoryId, String state) {

        //使用pagehelper插件完成分页，需要引入依赖,pageNum为页数，pageSize为每页多少条数据
        PageHelper.startPage(pageNum, pageSize);
        //查询数据集（注意分页插件已完成分页不需要使用limit）
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
       List<Article> list= articleMapper.articleList(categoryId,userId,state);
       //将结果集强转为Page,因为分页的数据集总量在这个对象中了
        Page<Article> page = (Page<Article>) list;
       //将数据总量和当前页的数据赋值到pageBean中进行返回
        PageBean<Article> pageBean = new PageBean<Article>();
        pageBean.setItems(page.getResult());
        pageBean.setTotal(page.getTotal());
        return pageBean;
    }
}
